<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-04 16:53:56
 * @LastEditTime: 2023-11-09 15:45:37
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description:检验单 返工刷卡 会自动删除检验单
 */

namespace App\Http\Services\Pro;


use App\Http\Services\Service;
use App\Models\BaseModel;
use App\Models\CustomerStorageInspectPackScrap;
use App\Repositories\ProProcessesInspectRepository;
use App\Repositories\ProProcessesPassRepository;
use App\Repositories\ProProcessesInspectPackRepository;

use Illuminate\Support\Facades\DB;

/**
 * @property ProProcessesInspectPackRepository $repository 
 * @author sunkaiyuan
 */
class InspectPackService extends Service
    {
    public function __construct(ProProcessesInspectPackRepository $repository)
        {
        $this->repository = $repository;

        }

    private function resetDataQuanTity(&$data, $formatter)
        {
        if ($formatter == 3) {
            $data['add_num']    = floor(($data['add_num'] ?? 0));
            $data['cut_num']    = floor(($data['cut_num'] ?? 0));
            $data['change_num'] = floor(($data['change_num'] ?? 0));
            $data['quantity']   = floor($data['quantity']);
            }
        else {
            $round_param = 0;
            if ($formatter == 2) {
                $round_param = 1;
                }
            $data['add_num']    = round($data['add_num'] ?? 0, $round_param);
            $data['cut_num']    = round($data['cut_num'] ?? 0, $round_param);
            $data['change_num'] = round($data['change_num'] ?? 0, $round_param);
            $data['quantity']   = round($data['quantity'], $round_param);
            $data['quantity']   = round($data['quantity'], $round_param);
            }
        }
    public function daypro()
        {
        $request     = request();
        $checkmac_id = $request->checkmac_id;
        $swipor_id   = $request->swipor_id;
        return $this->repository
            ->whereCheckmac_id($checkmac_id)
            ->where("swiped_at", ">=", date("Y-m-d") . " 00:00:00")
            ->whereSwipor_id($swipor_id)->sum('quantity');
        }
    protected function save()
        {
        $data = request()->toArray();

        $data['swiped_at']  = date("Y-m-d H:i:s");
        $auxiliary_quantity = $data['auxiliary_quantity'] = $data['auxiliary_quantity'] ?? 1;

        if (isEmpty($data['check_quantity'] ?? ""))
            $data['check_quantity'] = 0;
        $check_quantity = $data['check_quantity'];
        //1 四舍五入，2一位小数，3向下取整
        $formatter = NULL;
        $quantity  = 0;
        $inspect_m = ProProcessesInspectRepository::whereId($data['inspect_id'])->first();
        if ($inspect_m) {
            // if ($inspect_m->status_id != 0) {
            //     fail("操作失败！单据{$inspect_m->status->name}");
            // }
            $formatter = $inspect_m->order->main?->check_formatter_id ?? 3;
        } else {
            fail("检验单不存在！！");
        }
        $this->repository->whereInspect_id($data['inspect_id'])->get()->filter(function ($v) use ($data, &$auxiliary_quantity, &$quantity, $check_quantity)
            {
            if ($v->reel == $data['reel']) {
                fail("卷号已存在，新增错误！");
                }
            $auxiliary_quantity += $v->auxiliary_quantity ?? 1;
            $quantity += $v->quantity;
            $check_quantity += $v->check_quantity;
            });

        $this->resetDataQuanTity($data, $formatter);
        $quantity += $data['quantity'];
        $data['check_point'] = 0;
        $hasScrap            = [];
        $data['scrap']       = array_map(function ($v) use ($data)
            {
            $v['main_id'] = $data['inspect_id'];

            return $v;
            }, json_decode($data['scrap'] ?? "{}", true));
        //同位置 同疵点，就保存一个
        $data['scrap'] = array_filter($data['scrap'], function ($v) use (&$hasScrap, &$data)
            {
            if (isset($hasScrap[((int) $v['position']) . "_" . $v['defect_id']])) {
                return false;
                }
            else {
                $data['check_point'] += $v['point'];
                $hasScrap[((int) $v['position']) . "_" . $v['defect_id']] = "";
                return true;
                }
            });
        if (isEmpty($data['style_id'])) {
            $data['style_id'] = 0;
            }
        $gdata   = $this->repository->autosave($data, false, 'scrap');
        $style_m = $gdata->style_mdl;
        //回写款号的实际米数
        if ($style_m) {
            $style_m->fect_quantity = $gdata->quantity;
            $style_m->save();
            }
        $inspect      = $gdata->main;
        $gdata->state = $inspect->state;
        $gdata->save();

        $inspect->check_point += $gdata->check_point;
        $inspect->check_quantity          = $check_quantity;
        $inspect->quantity                = $quantity;
        $inspect->auxiliary_quantity      = $auxiliary_quantity;
        $inspect->reel                    = $inspect->pack->count();
        $inspect->fect_quantity           = $quantity + $gdata->quantity;
        $inspect->fect_auxiliary_quantity = $auxiliary_quantity + $gdata->auxiliary_quantity;
        $inspect->save();
        if ($inspect->status_id == 1) {
            $this->repository->stockIn($gdata);
            }
        return $this->getBarCode($gdata);
        }

    public function getBarCode($gdata = NULL)
        {
        $gdata                 = $gdata ?? $this->repository->whereId(request("id"))->first();
        $inspect               = $gdata->main;
        $data['quantity']      = $inspect->quantity;
        $data['pack_quantity'] = $gdata->quantity;
        $data['reel']          = $inspect->reel + 1;

        // 优先使用内部标签，否则使用外部标签
        $inside_filepath = $inspect->order?->inside_barcode?->filepath ?: $inspect->order?->main->inside_barcode?->filepath;
        if ($inside_filepath && file_exists("barcode" . $inside_filepath)) {
            $data['inside_struct'] = file_get_contents("barcode" . $inside_filepath);
            $data['needprint_in'] = "1";
        } else if ($inspect->order?->main->inside_barcode?->filepath && file_exists("barcode" . $inspect->order?->main->inside_barcode?->filepath)) {
            $data['inside_struct'] = file_get_contents("barcode" . $inspect->order?->main->inside_barcode?->filepath);
            $data['needprint_in'] = "1";
        }else{
            $data['needprint_in'] = "0";
        }
        
        // 优先使用内部标签，否则使用外部标签
        $outside_filepath = $inspect->order?->outside_barcode?->filepath ?: $inspect->order?->main->outside_barcode?->filepath;
        if ($outside_filepath && file_exists("barcode" . $outside_filepath)) {
            $data['outside_struct'] = file_get_contents("barcode" . $outside_filepath);
            $data['needprint_out'] = "1";
        } else if($inspect->order?->main->outside_barcode?->filepath && file_exists("barcode" . $inspect->order?->main->outside_barcode?->filepath)){
            $data['outside_struct'] = file_get_contents("barcode" . $inspect->order?->main->outside_barcode?->filepath);
            $data['needprint_out'] = "1";
        } else {
            $data['needprint_out'] = "0";
        }

        $data['data'] = [
            "row" => [
                'barcode'                => $inspect->code . "_" . $gdata->id,
                'code'                   => $inspect->code,
                'cust_order'             => $inspect->cust_order,
                'order_code'             => $inspect->order?->code,
                'unit_name'              => $gdata->unit_id == 3 ? "米" : "码",
                'en_unit_name'           => $gdata->unit_id == 3 ? "m" : "yd",
                'style'                  => $gdata->style,
                'grade'                  => $gdata->grade,
                'check_point'            => $gdata->check_point,
                'volume'                 => 1,
                'material_code'          => $inspect->material->code,
                'dyelot'                 => $inspect->dyelot,
                'material_spec'          => $inspect->material->spec,
                'material_name'          => $inspect->material->name,
                'mcn'                    => $inspect->material->code . "/" . $inspect->material->name,
                'material_width'         => $gdata->material->width,
                'material_weight'        => $gdata->material->weight,
                'sort'                   => $gdata->reel,
                'color_name'             => $inspect->color_name,
                'meter_addNum'           => $gdata->change_num == 0 ? $gdata->quantity : ($gdata->quantity . "+" . $gdata->change_num),
                'addNum'                 => $gdata->add_num,
                'cutNum'                 => $gdata->cut_num,
                'changeNum'              => $gdata->change_num,
                'meter'                  => $gdata->quantity,
                'yardage'                => $gdata->quantity,
                'check_weight'           => $gdata->check_weight,
                'checker_name'           => $gdata->swipor?->name,
                'checkmac_name'          => $gdata->checkmac?->name,
                'craft_name'             => $inspect->order->craft_remark ?: '',
                'customer_material_name' => $inspect->order?->custno,
                'lable_color'            => $inspect->order?->label_color,
                'lable_material'         => $inspect->order?->label_material,
                'comp'                   => $inspect->order?->materialcf,
                'depot_name'             => $inspect->location->name,
                'swiped_at'              => $gdata->swiped_at,
                'net_weight'             => $gdata->net_weight,
                'gross_weight'           => $gdata->tube_weight,
                // 指标
                'customer_code'         => $inspect->order?->customer?->code ?: "",
                'sample_code'           => $inspect->order?->sample_code  ?: "",
                'soak'                  => $inspect->order?->soak  ?: "",
                'water_pressure'        => $inspect->order?->water_pressure  ?: "",
                'strip_index_name'      => $inspect->order?->strip_index?->name ?: "",
                'washed_index_name'     => $inspect->order?->washed_index?->name ?: "",
                'width'                 => $inspect->order?->width ?: "",
                'weight'                => $inspect->order?->weight ?: "",
            ]
        ];

        return $data;
        }
    protected function delete($ids = null)
        {
        $inspect = $order = null;
        $this->repository->whereIn("id", $ids ?? $this->getRequestIds())->get()->filter(function ($v) use (&$inspect, &$order)
            {
            // if ($v->main->status_id != 0) {
            //     fail("操作失败！单据{$v->main->status->name}");
            //     }
            if ($inspect == null)
                $inspect = $v->main;

            $v->scrap->filter(fn($v) => $v->delete());
            $inspect->reel -= 1;
            $inspect->check_point -= $v->check_point;
            $inspect->quantity -= $v->quantity;
            $inspect->auxiliary_quantity -= $v->auxiliary_quantity;
            $inspect->fect_auxiliary_quantity -= $v->auxiliary_quantity;
            $inspect->fect_quantity -= $v->quantity;
            if ($inspect->status_id == 1) {
                $this->repository->noStockIn($v);
                }
            $v->delete();
            });
        $order && $order->save();
        return $inspect && $inspect->save();
        }

    protected function remove()
        {
        $this->repository->whereIn("id", $this->getRequestIds())->withTrashed()->get()->filter(function ($v)
            {
            $v->forceDelete();
            });
        }

    protected function restore()
        {
        $inspect = $order = null;
        return $this->repository->whereIn("id", $this->getRequestIds())->withTrashed()->get()->filter(function ($v) use (&$inspect, &$order)
            {
            $v->restore();
            $v->scrap->filter(fn($v) => $v->restore());

            if ($inspect == null)
                $inspect = $v->main;

            if ($inspect->status_id == 1) {
                $this->repository->stockIn($v);
                }
            $inspect->reel += 1;
            $inspect->check_point += $v->check_point;
            $inspect->quantity += $v->quantity;
            $inspect->auxiliary_quantity += $v->auxiliary_quantity;
            $inspect->fect_auxiliary_quantity += $v->auxiliary_quantity;
            $inspect->fect_quantity += $v->quantity;
            });
        }
    public function list()
        {
        $data = $this->repository->condition(request())->getGrid();
        return $data;
        }
    public function listgrid()
        {
        if (request("deleted") == "-1") {
            $this->repository->withTrashed()->whereNotNull("deleted_at");
            }
        $data = $this->repository->condition(request())->getList();
        // return $data;
        return $data->map(function ($v)
            {
            return createGrid($v->toArray());
            });
        }

    }